<?php
class PostController extends DbConnector {
	private $feedContent;
	private $tag;
	private $name;
	private $feed;
	private $torrent;
	private $output;
	private $post;

	function __construct($post) {
		// add a new podcast or delete one?
		if(isset($post["addFeed"])) {
			$this->post = $post;
			$this->post["newPodcast"] = $post["tag"];

			$this->tag = @mysql_real_escape_string($post["tag"]);
			$this->name = @mysql_real_escape_string($post["name"]);
			$this->feed = @mysql_real_escape_string($post["feed"]);
			$this->torrent = @mysql_real_escape_string($post["torrentfeed"]);

			$this->savePodcast();
		} elseif(isset($_POST["delPodcast"])) {
			$this->tag = @mysql_real_escape_string($_POST["delPodcast"]);
			$this->deletePodcast();
		} else {
			// initialize $post anyway
			$this->clearPostData();
		}
	}

	public function getOutput() {
		return $this->output;
	}

	public function getPostData() {
		return $this->post;
	}

	public function clearPostData() {
		$this->post = array("tag" => "",
		                    "name" => "",
		                    "feed" => "",
		                    "torrentfeed" => "",
		                    "newPodcast" => "");
	}

	private function deletePodcast() {
		$query = "DELETE FROM `pp_podcasts` WHERE tag = '".$this->tag."';";
		self::$db->query($query);

		$this->output["success"] = "Podcast deleted.<br><br>\n\n";
	}

	private function savePodcast() {
		if($this->tag != "" && $this->name != "") {
			if($this->testFeed($this->torrent) && $this->testFeed($this->feed)) {
				$logo = Logo::separateFromContent($this->feedContent);

				$query = "INSERT INTO `pp_podcasts`(`tag`, `name`, `feed`, `torrentfeed`, `logo`) ";
				$query .= "VALUES('".$this->tag."', '".$this->name."', '".$this->feed."', '".$this->torrent."', '".$logo["image"]."')";

				self::$db->query($query);
				$this->output["success"] = "Successfully added.<br><br>\n\n";
				$this->clearPostData();

				// insert the tag of added podcast to scroll window
				$this->post["newPodcast"] = $this->tag;
			} else {
				$this->post["newPodcast"] = "footer";
			}
		} else {
			$this->output["error"] = "Please make an entry for each field.";
			$this->post["newPodcast"] = "footer";
		}
	}

	private function testFeed($feed) {
		$res = true ;

		$this->feedContent = @file_get_contents($feed);

		if(!@simplexml_load_string($this->feedContent)) {
			$this->output["error"] = "Can\'t read feed: <i>$feed</i>";
			$res = false;
		}

		return $res;
	}
}

?>